package aa.jx.cartFunction.service;

import aa.jx.cartFunction.mapper.*;
import aa.jx.cartFunction.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final CartMapper cartMapper;
    private final AddressMapper addressMapper;
    private final ProductMapper productMapper;

    @Autowired
    public OrderServiceImpl(OrderMapper orderMapper,
                            OrderItemMapper orderItemMapper,
                            CartMapper cartMapper,
                            AddressMapper addressMapper,
                            ProductMapper productMapper) {
        this.orderMapper = orderMapper;
        this.orderItemMapper = orderItemMapper;
        this.cartMapper = cartMapper;
        this.addressMapper = addressMapper;
        this.productMapper = productMapper;
    }

    @Override
    public List<AddressDTO> getUserAddresses(Integer userId) {
        return addressMapper.selectAddressesByUserId(userId);
    }

    @Override
    @Transactional
    public OrderDTO createOrder(Integer userId, Integer addressId, List<Integer> cartItemIds) {
        // 1. 验证地址是否存在
        AddressDTO address = addressMapper.getAddressById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new RuntimeException("地址不存在或无权使用");
        }

        // 2. 获取购物车商品
        List<CartProductDTO> cartItems = cartMapper.selectCartItemsByIds(cartItemIds);
        if (cartItems.isEmpty()) {
            throw new RuntimeException("购物车商品不存在");
        }

        // 3. 计算订单总金额
        BigDecimal totalAmount = cartItems.stream()
                .map(item -> item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 4. 计算运费（假设固定10元）
        BigDecimal freightAmount = new BigDecimal("10.00");

        // 5. 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setAddressId(addressId);
        order.setTotalAmount(totalAmount);
        order.setPaymentAmount(totalAmount.add(freightAmount));
        order.setFreightAmount(freightAmount);
        order.setStatus(0); // 待支付
        order.setCreated(new Date());

        orderMapper.insertOrder(order);

        // 6. 创建订单项
        for (CartProductDTO cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(cartItem.getProduct().getId());
            orderItem.setProductName(cartItem.getProduct().getName());
            orderItem.setProductImage(cartItem.getProduct().getMainImage());
            orderItem.setProductPrice(cartItem.getProduct().getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setTotalPrice(cartItem.getProduct().getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())));

            orderItemMapper.insertOrderItem(orderItem);

            // 减少商品库存
            productMapper.reduceStock(cartItem.getProduct().getId(), cartItem.getQuantity());
        }

        // 7. 从购物车中移除已结算的商品
        cartMapper.deleteCartItemsByIds(cartItemIds);

        // 8. 返回订单详情
        return orderMapper.getOrderById(order.getId());
    }

    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
    }
}